#include "en.hpp"
#include "ship.hpp"
#include "tile.hpp"
#include "room.hpp"
int64_t en::time;
std::vector< std::shared_ptr<ship> > en::shipList;
std::vector< std::shared_ptr<sf::Texture> > en::texList;
sf::RenderWindow en::window;

/* Loads texture from file, inserts it into global texture list and returns
   shared_ptr to the texture. Returns null if load failed.
*/
std::shared_ptr<sf::Texture> en::loadTex(const std::string& fileName)
{
	sf::Texture tex;
	if( !tex.loadFromFile(fileName) )
	{
		return(nullptr);
	}
	else
	{
		std::shared_ptr<sf::Texture> texPtr = std::make_shared<sf::Texture>(tex);
		en::texList.push_back(texPtr);
		return(texPtr);
	}
}

std::shared_ptr<ship> en::loadShip( const std::string& fileName, std::shared_ptr<sf::Texture> tex)
{
	std::ifstream stream(fileName);

	if( !stream.is_open() )
	{
		return(nullptr);
	}
	else
	{
		std::string entry;
		std::string line;
		size_t w = 0;
		size_t w1= 0;
		size_t h = 0;
		std::vector<tile> tiles;
		tile tmpTile;

		/// Extracts ship layout first
		do
		{
			std::getline(stream, line);
			std::stringstream lineStream(line, std::ios_base::in);
			w1 = 0;
			do
			{
				entry.clear();
				std::getline(lineStream, entry, ',');
				tmpTile.fromString(entry);
				tiles.push_back(tmpTile);

				w1++;
			} while( !lineStream.eof() );

			if(w != 0)
			{
				if(w1 != w)
				{
					// inconsistent line lengths in file
					stream.close();
					return(nullptr);
				}
			}
			w = w1;

			h++;
		} while( line.find("##", 0) == std::string::npos );


		std::shared_ptr<ship> shipPtr = std::make_shared<ship>(w,h);
		shipPtr->setTex(tex);

		for(size_t j = 0; j < h; j++)
		{
			for(size_t i = 0; i < w; i++)
			{
				shipPtr->setTile(i, j, tiles[i+j*w]);
			}
		}

		/// Fills in rooms according to layout
		std::shared_ptr<room> roomPtr = std::make_shared<room>();
		shipPtr->floodRoom(0,0, roomPtr);
		roomPtr->ID = 0;
		shipPtr->roomOut = roomPtr;

		for(size_t j = 0; j < h; j++)
		{
			for(size_t i = 0; i < w; i++)
			{
				shipPtr->makeRoom(i,j);
			}
		}

		/// Load subsystems
		do
		{
			std::getline(stream, line);
			std::stringstream lineStream(line, std::ios_base::in);
			// extract useful data from this line. Assume 1 line per subsystem.
			// switch based on the first, let's say, three characters.

		} while( line.find("##", 0) == std::string::npos && !stream.eof() );


		shipPtr->refreshDisp();

		stream.close();

		return(shipPtr);

	}
}








